'use strict';

const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Message extends Model {
    static associate(models) {
      Message.belongsTo(models.Contact, { foreignKey: 'contactId' });
      Message.belongsTo(models.User, { foreignKey: 'userId' });
      Message.belongsTo(models.WhatsappSession, { foreignKey: 'sessionId' });
    }
  }
  
  Message.init({
    contactId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'contacts',
        key: 'id'
      }
    },
    sessionId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'whatsapp_sessions',
        key: 'id'
      }
    },
    direction: {
      type: DataTypes.ENUM('inbound', 'outbound'),
      allowNull: false
    },
    fromMe: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    type: {
      type: DataTypes.ENUM('text', 'image', 'video', 'audio', 'document', 'location', 'contact', 'system'),
      defaultValue: 'text',
      allowNull: false
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    contentType: {
      type: DataTypes.STRING,
      defaultValue: 'text'
    },
    originalContent: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    hasSensitive: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    mediaUrl: {
      type: DataTypes.STRING,
      allowNull: true
    },
    mimeType: {
      type: DataTypes.STRING,
      allowNull: true
    },
    whatsappMessageId: {
      type: DataTypes.STRING,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('pending', 'sent', 'delivered', 'read', 'failed'),
      defaultValue: 'sent'
    },
    isRead: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      }
    }
  }, {
    sequelize,
    modelName: 'Message',
    tableName: 'messages',
    indexes: [
      {
        name: 'messages_contact_id',
        fields: ['contactId']
      },
      {
        name: 'messages_session_id',
        fields: ['sessionId']
      },
      {
        name: 'messages_whatsapp_message_id',
        fields: ['whatsappMessageId']
      },
      {
        name: 'messages_created_at',
        fields: ['createdAt']
      }
    ]
  });
  
  return Message;
}; 